package com.csj.mvvm.api.retrofit

import com.csj.mvvm.App
import com.csj.mvvm.api.ApiService
import com.csj.mvvm.api.URLConstant
import com.csj.mvvm.api.interceptor.BearInterceptor
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException
import java.io.InputStream
import java.security.KeyStore
import java.security.SecureRandom
import java.security.cert.CertificateFactory
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManagerFactory

class RetrofitClient2 {

    companion object {
        private var instance: RetrofitClient2? = null
        fun getInstance() = instance ?: RetrofitClient2().also { instance = it }

        private lateinit var retrofit: Retrofit
    }

    private var cookieJar: PersistentCookieJar = PersistentCookieJar(
        SetCookieCache(),
        SharedPrefsCookiePersistor(App.instance)
    )

    init {
        retrofit = Retrofit.Builder()
            .client(getOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(URLConstant.BASE_URL2)
            .build()
    }

    private fun getOkHttpClient(header: Boolean = false): OkHttpClient {
        //https网络请求验证.cer证书
        var inputStream: InputStream? = null
        try {
            inputStream = App.instance.assets.open("ali_root.cer")
        } catch (e: java.lang.Exception) {
        }
        return OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .cookieJar(cookieJar)
            .addInterceptor(BearInterceptor())
            .sslSocketFactory(setCertificates(inputStream))
            .hostnameVerifier { _, _ -> true }
            .build()
    }

    private fun setCertificates(vararg certificates: InputStream?): SSLSocketFactory? {
        try {
            //证书工厂。此处指明证书的类型
            val certificateFactory = CertificateFactory.getInstance("X.509")
            //创建一个证书库
            val keyStore = KeyStore.getInstance(KeyStore.getDefaultType())
            keyStore.load(null)
            var index = 0
            for (certificate in certificates) {
                val certificateAlias = (index++).toString()
                //将证书导入证书库
                keyStore.setCertificateEntry(
                    certificateAlias,
                    certificateFactory.generateCertificate(certificate)
                )
                try {
                    certificate?.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            //取得SSL的SSLContext实例
            val sslContext = SSLContext.getInstance("TLS")
            val trustManagerFactory =
                TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
            trustManagerFactory.init(keyStore)
            sslContext.init(null, trustManagerFactory.trustManagers, SecureRandom())
            return sslContext.socketFactory
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    fun create(): ApiService = retrofit.create(
        ApiService::class.java
    )

}